package com.xfcycle.zebrabikegp.activity;

import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.google.gson.Gson;
import com.xfcycle.zebrabikegp.R;
import com.xfcycle.zebrabikegp.assist.BlueToothAssist;
import com.xfcycle.zebrabikegp.bean.SportDataResult;
import com.xfcycle.zebrabikegp.constant.BluetoothDeviceConstant;
import com.xfcycle.zebrabikegp.constant.SpConstant;
import com.xfcycle.zebrabikegp.constant.TimingConstant;
import com.xfcycle.zebrabikegp.constant.ToastConstant;
import com.xfcycle.zebrabikegp.customView.CircleProgressBar;
import com.xfcycle.zebrabikegp.database.SportDataDao;
import com.xfcycle.zebrabikegp.listener.OnTimeOutListener;
import com.xfcycle.zebrabikegp.util.DateFormatUtil;
import com.xfcycle.zebrabikegp.util.GetUUIDUtil;
import com.xfcycle.zebrabikegp.util.HandleDataByBLEUtil;
import com.xfcycle.zebrabikegp.util.HandleDataBySharePreferencesUtil;
import com.xfcycle.zebrabikegp.util.TimingThreadUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 运动数据页面
 * <p>
 * Created by xFcycle on 2017/6/19.
 */

public class SportDataActivity extends RootActivity {
    private String TAG = "SportDataActivity";

    private ImageView iv_sport_data_back;
    private ImageView iv_menu;
    private LinearLayout ll_menu_list;
    private TextView tv_sport_target_set;
    private TextView tv_sport_target_unit;
    private TextView tv_sport_data_target;
    private CircleProgressBar cp_sport_data_finish;

    private TextView tv_sport_data_calorie;
    private TextView tv_sport_data_mileage;
    private TextView tv_sport_data_unit;
    private TextView tv_sport_data_time;

    private int orange;
    private int white;
    private LineChart lc_sport_data_record;

    private PopupWindow pw_edit_sport_target;
    private EditText et_edit_sport_target;
    private TextView tv_sport_target_cancel;
    private TextView tv_sport_target_save;

    private HandleDataBySharePreferencesUtil handleDataBySharePreferencesUtil;
    private SdHandleDataFromBleReceiver sdHandleDataFromBleReceiver;
    private String uid;

    private Long dateToday;
    //折线图Y轴数据集
    private List<Entry> yValues;

    private HandleDataByBLEUtil handleDataByBLEUtil;

    private TimingThreadUtil timingThreadUtil;

    private LineData sportDataRecord;

    private SportDataDao sportDataDao;
    private SportDataDTO sportDataDTO;

    //判断当前计量单位是公里还是英里
    private boolean isMI = true;
    private String kmTag = "km";
    private String miTag = "mi";
    private Double kmRatio = 1.6;
    private Integer targetLimit = 200;
    private Integer sportTarget;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sport_data);

        uid = getIntent().getExtras().getString("uid");

        initView();
        initViewListener();
        setViewContent();

        drawSportTargetPopWindow();

        //开启查询运动数据定时线程
        if (BlueToothAssist.isUnlock) {
            timingThreadUtil.openThread(TimingConstant.SPORT_DATA_THREAD_NAME, TimingConstant.SPORT_DATE_TIME);
        }

        //注册从蓝牙设备接收数据广播
        sdHandleDataFromBleReceiver = new SdHandleDataFromBleReceiver();
        registBroadcastReceiverAtActivity(sdHandleDataFromBleReceiver, BluetoothDeviceConstant.GET_DATA_FROM_BLUETOOTH_BROADCAST_RECEIVER_ACTION);
    }

    @Override
    protected void onResume() {
        super.onResume();
        drawSportDataHistoryChat();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //关闭查询运动数据定时线程
        timingThreadUtil.closeThread(TimingConstant.SPORT_DATA_THREAD_NAME);

        //回收广播接收者
        if (null != sdHandleDataFromBleReceiver) {
            unregisterReceiver(sdHandleDataFromBleReceiver);
        }
    }

    private void initView() {
        iv_sport_data_back = (ImageView) findViewById(R.id.iv_sport_data_back);
        iv_menu = (ImageView) findViewById(R.id.iv_menu);
        ll_menu_list = (LinearLayout) findViewById(R.id.ll_menu_list);
        tv_sport_target_set = (TextView) findViewById(R.id.tv_sport_target_set);
        tv_sport_target_unit = (TextView) findViewById(R.id.tv_sport_target_unit);
        lc_sport_data_record = (LineChart) findViewById(R.id.lc_sport_data_record);
        cp_sport_data_finish = (CircleProgressBar) findViewById(R.id.cp_sport_data_finish);
        tv_sport_data_target = (TextView) findViewById(R.id.tv_sport_data_target);

        tv_sport_data_calorie = (TextView) findViewById(R.id.tv_sport_data_calorie);
        tv_sport_data_mileage = (TextView) findViewById(R.id.tv_sport_data_mileage);
        tv_sport_data_unit = (TextView) findViewById(R.id.tv_sport_data_unit);
        tv_sport_data_time = (TextView) findViewById(R.id.tv_sport_data_time);

        handleDataBySharePreferencesUtil = HandleDataBySharePreferencesUtil.getInstance(this);

        dateToday = System.currentTimeMillis();

        orange = Color.rgb(245, 168, 32);
        white = Color.rgb(255, 255, 255);

        handleDataByBLEUtil = HandleDataByBLEUtil.getInstance(this, -1);

        timingThreadUtil = TimingThreadUtil.getInstance(TimingConstant.SPORT_DATA_THREAD_NAME, new OnTimeOutListener() {
            @Override
            public void timeOut() {
                handleDataByBLEUtil.sendDataToDevice("b");
            }
        });

        sportDataDao = new SportDataDao(this);

        sportDataDTO = new SportDataDTO();
    }

    private void initViewListener() {
        //设置回退监听事件
        iv_sport_data_back.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                closeActivity();
            }
        });

        //展示菜单栏
        iv_menu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(View.VISIBLE == ll_menu_list.getVisibility()){
                    ll_menu_list.setVisibility(View.GONE);
                }else {
                    ll_menu_list.setVisibility(View.VISIBLE);
                }
            }
        });

        //修改运动目标
        tv_sport_target_set.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showSportTargetPopWindow();
                ll_menu_list.setVisibility(View.GONE);
            }
        });

        //修改计量单位
        tv_sport_target_unit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(null == sportTarget){
                    try {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(SportDataActivity.this.getApplicationContext(), ToastConstant.MODIFY_SPORT_TARGET_FAIL, Toast.LENGTH_SHORT).show();
                            }
                        });
                    }catch (Exception e){
                        e.printStackTrace();
                        return;
                    }
                }
                isMI = !isMI;

                //更改目标设置
                sportTarget = (int)(sportTarget * (isMI ? 1 / kmRatio : kmRatio) + 0.5);
                tv_sport_data_target.setText("Target " + sportTarget + (isMI ? miTag : kmTag));

                setCpBarMax(sportTarget);
                //sp记录运动目标
                Map<String, String> targetParams = new HashMap<>();
                targetParams.put(uid + "target", sportTarget+ "");
                handleDataBySharePreferencesUtil.putDateIntoSharePre(APP_INFO_SP_NAME, targetParams);

                //更改当前数据
                CharSequence mileageStr = tv_sport_data_mileage.getText();
                if (null != mileageStr && !"".equals(mileageStr.toString())) {
                    double mileageDou = Double.parseDouble(mileageStr.toString());
                    if (mileageDou > 0) {
                        mileageDou = mileageDou * (isMI ? 1 / kmRatio : kmRatio);
                        tv_sport_data_mileage.setText(mileageDou + "");
                        setCpBarProgress((int)mileageDou);
                    }
                }
                tv_sport_data_unit.setText(isMI ? miTag : kmTag);

                //sp记录单位
                Map<String, String> unitParams = new HashMap<>();
                unitParams.put(uid + "unit", isMI ? miTag : kmTag);
                handleDataBySharePreferencesUtil.putDateIntoSharePre(APP_INFO_SP_NAME, unitParams);

                ll_menu_list.setVisibility(View.GONE);
            }
        });
    }

    private void setViewContent() {
        //初始化计量单位
        String unit = handleDataBySharePreferencesUtil.getDateFromSharePre(APP_INFO_SP_NAME, uid + "unit");
        if (null == unit || "".equals(unit) || miTag.equals(unit)) {
            isMI = true;
            tv_sport_data_unit.setText(miTag);
        } else {
            isMI = false;
            tv_sport_data_unit.setText(kmTag);
        }

        //初始化运动目标历史记录
        String target = handleDataBySharePreferencesUtil.getDateFromSharePre(APP_INFO_SP_NAME, uid + "target");

        if(null == target || "".equals(target)){
            target = "200";
        }

        setCpBarMax(Integer.parseInt(target));
        setCpBarProgress(0);

        String targetText = "Target " + target + (isMI ? miTag : kmTag);
        sportTarget = Integer.parseInt(target);
        tv_sport_data_target.setText(targetText);
    }

    /***********************************************************************************************/
    /**                      绘制本次骑行运动数据CircleProgressBar                                  **/
    /***********************************************************************************************/

    /**
     * 设置圆形进度条最大值
     *
     * @param max 进度条最大值
     */
    private void setCpBarMax(int max) {
        cp_sport_data_finish.setMax(max);
    }

    /**
     * 设置圆形进度条当前进度
     *
     * @param progress 进度条当前进度
     */
    private void setCpBarProgress(int progress) {
        cp_sport_data_finish.setProgress(progress);
    }

    /***********************************************************************************************/
    /**                          绘制运动记录线性图表历史记录                                        **/
    /***********************************************************************************************/

    /**
     * 绘制运动数据历史纪录表
     */
    private void drawSportDataHistoryChat() {
        //获取运动数据线性表数据
        sportDataRecord = getSportDataRecord(7);

        //展示运动数据线性表
        showSportDataHistoryChat(lc_sport_data_record, sportDataRecord, Color.rgb(51, 51, 51));
    }

    /**
     * 获取运动数据线性表数据
     *
     * @param count x轴坐标范围
     * @return
     */
    private LineData getSportDataRecord(int count) {
        Long daySeconds = Long.valueOf(24 * 3600 * 1000);

        //X轴，Y轴数据
        List<String> xValues = new ArrayList<>();
        yValues = new ArrayList<>();

        Log.e(TAG, "getSportDataRecord: -----------------------------" + dateToday + "-----" + DateFormatUtil.getCurrentDate(dateToday));

        //设置x坐标轴的下标
        for (int i = 0; i <= count; i++) {
            String strData = DateFormatUtil.getCurrentDate(dateToday - (6 - i) * daySeconds);
            xValues.add(strData.substring(strData.indexOf("-") + 1));

            if (i == count) {
                break;
            }
            if (null == BlueToothAssist.currentConnectBikeId) {
                yValues.add(new Entry(0, i));
                continue;
            }

            //查询
            SportDataResult sportDataResultToday = sportDataDao.querySportData(BlueToothAssist.currentConnectBikeId, strData);
            Log.i(TAG, "getSportDataRecord: -------------------- 查询数据库得到的历史运动数据：" + sportDataResultToday.getCalorie());
            //添加折线图数据
            try {
                yValues.add(new Entry(Float.parseFloat(sportDataResultToday.getCalorie()), i));
            } catch (Exception e) {
                Log.w(TAG, "getSportDataRecord: ------ 数据类型错误");
            }
        }

        LineDataSet lineDataSet = new LineDataSet(yValues, "Sports Statistics");

        //通过y轴设置折线参数
        lineDataSet.setLineWidth(2f); // 线宽
        lineDataSet.setCircleSize(3f);// 显示的圆形大小
        lineDataSet.setColor(orange);// 显示颜色
        lineDataSet.setCircleColor(orange);// 圆形的颜色
        lineDataSet.setHighLightColor(orange); // 高亮的线的颜色
        lineDataSet.setHighlightEnabled(true); //十字定位线是否展示
        lineDataSet.setValueTextColor(orange); //数值显示的颜色
        lineDataSet.setValueTextSize(10f);     //数值显示的大小

        List<LineDataSet> lineDataSets = new ArrayList<>();
        lineDataSets.add(lineDataSet);

        //创建LineData
        return new LineData(xValues, lineDataSets);
    }

    private void showSportDataHistoryChat(LineChart lineChart, LineData lineData, int color) {
        lineChart.setDrawBorders(true); //在折线图上添加边框
        lineChart.setDescription("Calories burned"); //数据描述
        lineChart.setDescriptionColor(white); //数据描述的颜色
        lineChart.setNoDataTextDescription("You need to provide data for the chart.");

        lineChart.setDrawGridBackground(false); //表格背景是否有
        lineChart.setBorderColor(white); //设置表格边界颜色
        lineChart.setGridBackgroundColor(orange); //表格的背景颜色，设置一个透明度

        lineChart.setTouchEnabled(true); //可点击

        lineChart.setDragEnabled(true);  //可拖拽
        lineChart.setScaleEnabled(true);  //可缩放

        lineChart.setPinchZoom(false);

        lineChart.setBackgroundColor(color); //设置背景颜色

        lineChart.setData(lineData);  //填充数据

        Legend mLegend = lineChart.getLegend(); //设置标示，就是那个一组y的value的

        mLegend.setForm(Legend.LegendForm.CIRCLE); //样式
        mLegend.setFormSize(6f); //字体
        mLegend.setTextColor(orange); //颜色

        lineChart.setVisibleXRange(1, 8);   //x轴可显示的坐标范围
        XAxis xAxis = lineChart.getXAxis();  //x轴的标示
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM); //x轴位置
        xAxis.setTextColor(white);    //字体的颜色
        xAxis.setTextSize(10f); //字体大小
        xAxis.setGridColor(orange);//网格线颜色
        xAxis.setDrawGridLines(true); //显示网格线

        YAxis axisLeft = lineChart.getAxisLeft(); //y轴左边标示
        YAxis axisRight = lineChart.getAxisRight(); //y轴右边标示
        axisLeft.setTextColor(white); //字体颜色
        axisLeft.setTextSize(10f); //字体大小
        axisLeft.setLabelCount(6, true); //显示格数
        axisLeft.setDrawGridLines(false);  //设置网格线不展示

        axisRight.setDrawAxisLine(false);
        axisRight.setDrawGridLines(false);
        axisRight.setDrawLabels(false);

        lineChart.animateX(2500);  //立即执行动画
    }

    /***********************************************************************************************/
    /**                              绘制修改运动目标里程PopWindow                                  **/
    /***********************************************************************************************/

    private void drawSportTargetPopWindow() {
        View view = getLayoutInflater().from(this).inflate(R.layout.item_edit_sport_target, null);
        et_edit_sport_target = (EditText) view.findViewById(R.id.et_edit_sport_target);
        tv_sport_target_cancel = (TextView) view.findViewById(R.id.tv_sport_target_cancel);
        tv_sport_target_save = (TextView) view.findViewById(R.id.tv_sport_target_save);

        //参数2,3为设置宽高
        pw_edit_sport_target = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        //设置外部背景
        pw_edit_sport_target.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        //设置外部可触摸
        pw_edit_sport_target.setOutsideTouchable(false);

        pw_edit_sport_target.setFocusable(true);

        tv_sport_target_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (null != pw_edit_sport_target && pw_edit_sport_target.isShowing()) {
                    pw_edit_sport_target.dismiss();
                }
            }
        });


        tv_sport_target_save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String tempTarget = et_edit_sport_target.getText().toString();
                if ("".equals(tempTarget)) {
                    return;
                }

                sportTarget = Integer.parseInt(tempTarget);

                //给出超出目标上限提示
                if (sportTarget > (isMI ? targetLimit : targetLimit * kmRatio)) {
                    try {
                        AlertDialog.Builder builder = new AlertDialog.Builder(SportDataActivity.this);
                        builder.setTitle(ToastConstant.DIALOG_NOTICE);
                        builder.setMessage(ToastConstant.DIALOG_OVER_RANGE);

                        builder.setPositiveButton(ToastConstant.DIALOG_OK, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        });

                        //展示提示框
                        builder.create().show();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                    return;
                }

                setCpBarMax(sportTarget);
                tv_sport_data_target.setText("Target " + sportTarget + (isMI ? miTag : kmTag));

                //将目标记录到sp中
                Map<String, String> params = new HashMap<>();
                params.put(uid + "target", tempTarget);
                handleDataBySharePreferencesUtil.putDateIntoSharePre(APP_INFO_SP_NAME, params);

                if (null != pw_edit_sport_target && pw_edit_sport_target.isShowing()) {
                    pw_edit_sport_target.dismiss();
                }
            }
        });
    }

    private void showSportTargetPopWindow() {
        if (null == pw_edit_sport_target) {
            return;
        }
        View parent = getWindow().getDecorView();
        //在父容器中间展示
        pw_edit_sport_target.showAtLocation(parent, Gravity.CENTER, 0, 0);
    }

    /***********************************************************************************************/
    /**                             处理从不同途径获得的数据                                         **/
    /***********************************************************************************************/

    /**
     * 处理从网络获得的数据
     *
     * @param webMsg
     */
    @Override
    public void dealDataFromWeb(Message webMsg) {
        super.dealDataFromWeb(webMsg);

        Gson gson = new Gson();
        String webResult = webMsg.obj.toString();
        int webSign = webMsg.what;

        Log.e(TAG, "dealDataFromWeb: -----------" + webResult);

        //判断在其他设备登陆
        if (webMsg.obj.toString().contains("you are signed in at another location") && REQUEST_SIGN_LOGOUT != webMsg.what) {
            //断开连接
            HandleDataByBLEUtil.disConnectDevice();
            //改变蓝牙辅助判断类的值
            BlueToothAssist.isConnect = false;
            BlueToothAssist.currentConnectBikeId = null;

            try {
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setTitle(ToastConstant.DIALOG_WARNING);
                builder.setMessage(ToastConstant.OTHER_DEVICE_LOGIN);

                builder.setPositiveButton(ToastConstant.DIALOG_I_KNOW, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        //回到登录界面
                        activityChange(LOGIN_ACTIVITY, null, null);
                        HandleDataByBLEUtil.disConnectDevice();
                    }

                });
                //展示提示框
                builder.create().show();
            } catch (Exception e) {
                Toast.makeText(this.getApplicationContext(), ToastConstant.OTHER_DEVICE_LOGIN, Toast.LENGTH_LONG).show();
                activityChange(LOGIN_ACTIVITY, null, null);
                HandleDataByBLEUtil.disConnectDevice();
            }
            return;
        }
    }

    /***********************************************************************************************/
    /**                                       自定义广播接收者类                                    **/
    /***********************************************************************************************/

    /**
     * 广播接收者类，负责接收从蓝牙发出的数据并对其进行处理
     */
    class SdHandleDataFromBleReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            String result = intent.getStringExtra("result");


            Log.w(TAG, "onReceive: ----------------- 运动数据：" + result);
            //获取到运动数据
            if (result.contains("^b|")) {
                String[] params = result.replace("$", "").replace("^b|", "").split(",");
                if (params.length <= 0) {
                    return;
                }
                sportDataDTO.setSpeed(Float.parseFloat(params[0]));
                sportDataDTO.setMileage(Float.parseFloat(params[1]) / 10);
                handleDataByBLEUtil.sendDataToDevice("e");
                return;
            }

            //获取到运动数据
            if (result.contains("^e|")) {
                String[] params = result.replace("$", "").replace("^e|", "").split(",");
                if (params.length <= 0) {
                    return;
                }
                sportDataDTO.setPower(Float.parseFloat(params[0]));
                sportDataDTO.setEnergy(Float.parseFloat(params[1]));
                dealSportData(sportDataDTO);
                return;
            }
        }
    }

    /***********************************************************************************************/
    /**                                      其他方法                                              **/
    /***********************************************************************************************/

    /**
     * 处理接收到的自行车运动数据
     *
     * @param sportDataDTO 接收到的自行车运动数据
     */
    private void dealSportData(SportDataDTO sportDataDTO) {

        if (null == sportDataDTO) {
            return;
        }

        //取出之前存储在sp中的骑行里程数 及当前连接自行车id
        HandleDataBySharePreferencesUtil handleDataBySharePreferencesUtil = HandleDataBySharePreferencesUtil.getInstance(this);
        String preMileage = handleDataBySharePreferencesUtil.getDateFromSharePre(SpConstant.SP_NAME, SpConstant.MILEAGE_KEY);
        String preTime = handleDataBySharePreferencesUtil.getDateFromSharePre(SpConstant.SP_NAME, SpConstant.SPORT_DATE_CURRENT_TIME_KEY);
        String currentDate = DateFormatUtil.getCurrentDate(dateToday);
        String currentConnectBikeId = BlueToothAssist.currentConnectBikeId;

        //将本时段运动数据存储到数据库中
        if (null != currentConnectBikeId && !"".equals(currentConnectBikeId)
                && !"".equals(preMileage) && null != preMileage
                && !"".equals(preTime) && null != preTime) {

            SportDataResult sportDataResult = new SportDataResult();
            sportDataResult.setUuid(GetUUIDUtil.getDatabaseUUID());
            sportDataResult.setBike_id(currentConnectBikeId);
            sportDataResult.setPace(sportDataDTO.getSpeed() + "");
            sportDataResult.setPower(sportDataDTO.getPower() + "");
            sportDataResult.setDistance(sportDataDTO.getMileage() + "");
            sportDataResult.setDate(currentDate);
            sportDataResult.setCalorie((10 * (sportDataDTO.getSpeed() * 0.36) * 70 * 1.05) + "");
            sportDataResult.setTarget(Integer.parseInt(tv_sport_data_target.getText().toString().replace("Target ", "").replace(isMI?miTag:kmTag,"")));

            sportDataDao.addSportData(sportDataResult);
        }

        //查询当天整个的运动数据,并将其展示在前台窗体中
        SportDataResult sportDataResultToday = sportDataDao.querySportData(currentConnectBikeId, currentDate);
        Double mileage = Double.parseDouble(sportDataResultToday.getDistance());
        tv_sport_data_calorie.setText(sportDataResultToday.getCalorie());
        mileage = mileage * (isMI ? 1 / kmRatio : 1);
        tv_sport_data_mileage.setText(mileage + "");
        tv_sport_data_time.setText(sportDataResultToday.getTime() / 60 + "");
        setCpBarProgress((int) (mileage > cp_sport_data_finish.getMax() ? cp_sport_data_finish.getMax() : mileage));

        //更新折线图数据
        yValues.remove(6);
        yValues.add(new Entry(Float.parseFloat(sportDataResultToday.getCalorie()), 6));
        lc_sport_data_record.notifyDataSetChanged();
        lc_sport_data_record.invalidate();

        //将当前里程和时间存到sp中
        Map<String, String> currentParams = new HashMap<>();
        currentParams.put(SpConstant.MILEAGE_KEY, sportDataDTO.getMileage() + "");
        currentParams.put(SpConstant.SPORT_DATE_CURRENT_TIME_KEY, dateToday + "");
        handleDataBySharePreferencesUtil.putDateIntoSharePre(SpConstant.SP_NAME, currentParams);
    }

    /**
     * 监听硬件回退事件
     */
    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        // 如果PopWindow存在则令其隐藏
        if (pw_edit_sport_target != null && pw_edit_sport_target.isShowing() && keyCode == KeyEvent.KEYCODE_BACK) {
            pw_edit_sport_target.dismiss();
            return true;
        }
        return super.onKeyUp(keyCode, event);
    }
}

/**===========================================================实体数据类====================================================================*/
class SportDataDTO {
    private Float speed;
    private Float mileage;
    private Float power;
    private Float energy;

    public Float getSpeed() {
        return speed;
    }

    public void setSpeed(Float speed) {
        this.speed = speed;
    }

    public Float getMileage() {
        return mileage;
    }

    public void setMileage(Float mileage) {
        this.mileage = mileage;
    }

    public Float getPower() {
        return power;
    }

    public void setPower(Float power) {
        this.power = power;
    }

    public Float getEnergy() {
        return energy;
    }

    public void setEnergy(Float energy) {
        this.energy = energy;
    }
}
